<template>
  <div class="bookmarks-container">
    <h1>我的收藏</h1>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-group">
        <label for="document-filter">文档:</label>
        <select id="document-filter" v-model="documentFilter" class="filter-select">
          <option value="">全部文档</option>
          <option v-for="doc in documents" :key="doc._id" :value="doc._id">
            {{ doc.title || doc.filename }}
          </option>
        </select>
      </div>
      
      <div class="filter-group">
        <label for="difficulty-filter">难度:</label>
        <select id="difficulty-filter" v-model="difficultyFilter" class="filter-select">
          <option value="">全部难度</option>
          <option value="EASY">简单</option>
          <option value="MEDIUM">中等</option>
          <option value="HARD">困难</option>
        </select>
      </div>
      
      <div class="filter-group search-group">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索收藏..." 
          class="search-input"
        />
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <p>加载中...</p>
    </div>
    
    <!-- 错误信息 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    
    <!-- 空状态 -->
    <div v-if="!loading && !bookmarks.length" class="empty-state">
      <p>您还没有收藏任何知识卡片</p>
      <router-link to="/cards" class="btn-browse-cards">
        浏览卡片库
      </router-link>
    </div>
    
    <!-- 书签列表 -->
    <div v-if="!loading && bookmarks.length" class="bookmarks-content">
      <!-- 书签列表 -->
      <div class="bookmarks-grid">
        <div 
          v-for="bookmark in filteredBookmarks" 
          :key="bookmark._id" 
          class="bookmark-item"
        >
          <div class="bookmark-header">
            <div class="bookmark-meta">
              <span :class="['difficulty', bookmark.card.difficulty.toLowerCase()]">
                {{ getDifficultyText(bookmark.card.difficulty) }}
              </span>
              
              <span v-if="bookmark.card.documentTitle" class="document-name" :title="bookmark.card.documentTitle">
                {{ bookmark.card.documentTitle }}
              </span>
            </div>
            
            <div class="bookmark-actions">
              <button 
                @click="removeBookmark(bookmark._id)" 
                class="btn-remove"
                :title="'取消收藏'"
              >
                <span>×</span>
              </button>
            </div>
          </div>
          
          <div class="bookmark-content">
            <h3>{{ bookmark.card.title }}</h3>
            <p>{{ truncateText(bookmark.card.content, 150) }}</p>
            
            <div v-if="bookmark.card.tags && bookmark.card.tags.length" class="card-tags">
              <span v-for="tag in bookmark.card.tags" :key="tag" class="tag">
                {{ tag }}
              </span>
            </div>
          </div>
          
          <div class="bookmark-footer">
            <router-link :to="`/cards/${bookmark.cardId}`" class="btn-view-card">
              查看详情
            </router-link>
            
            <span class="bookmark-date">
              收藏于 {{ formatDate(bookmark.createdAt) }}
            </span>
          </div>
        </div>
      </div>
      
      <!-- 分页控件 -->
      <div v-if="totalPages > 1" class="pagination">
        <button 
          @click="changePage(currentPage - 1)" 
          :disabled="currentPage === 1"
          class="btn-page"
        >
          上一页
        </button>
        
        <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
        
        <button 
          @click="changePage(currentPage + 1)" 
          :disabled="currentPage === totalPages"
          class="btn-page"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';
import { documentApi } from '@/services/api';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 状态变量
const loading = ref(false);
const error = ref('');
const bookmarks = ref([]);
const documents = ref([]);
const documentFilter = ref('');
const difficultyFilter = ref('');
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(12);
const totalBookmarks = ref(0);

// 从路由参数获取初始筛选条件
onMounted(async () => {
  if (route.query.document) {
    documentFilter.value = route.query.document;
  }
  
  if (route.query.difficulty) {
    difficultyFilter.value = route.query.difficulty;
  }
  
  if (route.query.search) {
    searchQuery.value = route.query.search;
  }
  
  if (route.query.page) {
    currentPage.value = parseInt(route.query.page) || 1;
  }
  
  // 获取文档列表
  await fetchDocuments();
  
  // 获取书签列表
  await fetchBookmarks();
});

// 监听筛选条件变化
watch([documentFilter, difficultyFilter, searchQuery], () => {
  // 重置页码
  currentPage.value = 1;
  
  // 更新路由参数
  updateRouteQuery();
});

// 监听页码变化
watch(currentPage, () => {
  // 更新路由参数
  updateRouteQuery();
});

// 计算属性
const filteredBookmarks = computed(() => {
  let result = [...bookmarks.value];
  
  // 按文档筛选
  if (documentFilter.value) {
    result = result.filter(bookmark => 
      bookmark.card.documentId === documentFilter.value
    );
  }
  
  // 按难度筛选
  if (difficultyFilter.value) {
    result = result.filter(bookmark => 
      bookmark.card.difficulty === difficultyFilter.value
    );
  }
  
  // 按搜索词筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(bookmark => 
      bookmark.card.title.toLowerCase().includes(query) || 
      bookmark.card.content.toLowerCase().includes(query) ||
      (bookmark.card.tags && bookmark.card.tags.some(tag => tag.toLowerCase().includes(query)))
    );
  }
  
  return result;
});

const totalPages = computed(() => {
  return Math.ceil(filteredBookmarks.value.length / pageSize.value) || 1;
});

// 方法
const fetchBookmarks = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    const response = await userStore.getBookmarks();
    
    if (response.success) {
      bookmarks.value = response.bookmarks;
      totalBookmarks.value = response.bookmarks.length;
    } else {
      error.value = response.error || '获取书签失败';
    }
  } catch (err) {
    error.value = '获取书签失败';
    console.error('获取书签失败:', err);
  } finally {
    loading.value = false;
  }
};

const fetchDocuments = async () => {
  try {
    const response = await documentApi.getAll();
    documents.value = response.data;
  } catch (err) {
    console.error('获取文档列表失败:', err);
  }
};

const updateRouteQuery = () => {
  const query = {};
  
  if (documentFilter.value) {
    query.document = documentFilter.value;
  }
  
  if (difficultyFilter.value) {
    query.difficulty = difficultyFilter.value;
  }
  
  if (searchQuery.value) {
    query.search = searchQuery.value;
  }
  
  if (currentPage.value > 1) {
    query.page = currentPage.value;
  }
  
  router.replace({ query });
};

const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
};

const removeBookmark = async (bookmarkId) => {
  try {
    const response = await userStore.removeBookmarkById(bookmarkId);
    
    if (response.success) {
      // 从列表中移除
      bookmarks.value = bookmarks.value.filter(bookmark => bookmark._id !== bookmarkId);
      totalBookmarks.value = bookmarks.value.length;
    }
  } catch (err) {
    console.error('移除书签失败:', err);
  }
};

// 辅助函数
const getDifficultyText = (difficulty) => {
  const difficultyMap = {
    'EASY': '简单',
    'MEDIUM': '中等',
    'HARD': '困难'
  };
  
  return difficultyMap[difficulty] || difficulty;
};

const truncateText = (text, maxLength) => {
  if (!text) return '';
  
  if (text.length <= maxLength) {
    return text;
  }
  
  return text.substring(0, maxLength) + '...';
};

const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};
</script>

<style scoped>
.bookmarks-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  margin-bottom: 2rem;
  color: #333;
}

/* 筛选区域样式 */
.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 2rem;
  padding: 1.5rem;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  flex-direction: column;
  min-width: 150px;
}

.search-group {
  flex-grow: 1;
}

.filter-group label {
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #555;
}

.filter-select, .search-input {
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9rem;
}

.filter-select:focus, .search-input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

/* 加载和错误状态样式 */
.loading-container, .empty-state {
  text-align: center;
  padding: 3rem;
  background-color: #f9f9f9;
  border-radius: 8px;
  color: #666;
}

.error-message {
  color: #ff3860;
  background-color: #feecf0;
  padding: 1rem;
  border-radius: 4px;
  margin-bottom: 1rem;
}

.btn-browse-cards {
  display: inline-block;
  padding: 0.75rem 1.5rem;
  background-color: #4CAF50;
  color: white;
  border-radius: 4px;
  text-decoration: none;
  margin-top: 1rem;
}

.btn-browse-cards:hover {
  background-color: #388E3C;
}

/* 书签网格样式 */
.bookmarks-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.bookmark-item {
  border: 1px solid #FFD700;
  border-radius: 8px;
  padding: 1.5rem;
  background-color: white;
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.1);
  display: flex;
  flex-direction: column;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.bookmark-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(255, 215, 0, 0.2);
}

.bookmark-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.bookmark-meta {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.difficulty {
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
  display: inline-block;
}

.difficulty.easy {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.difficulty.medium {
  background-color: #fff8e1;
  color: #ff8f00;
}

.difficulty.hard {
  background-color: #ffebee;
  color: #c62828;
}

.document-name {
  font-size: 0.8rem;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}

.bookmark-actions {
  display: flex;
  gap: 0.5rem;
}

.btn-remove {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #F44336;
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
}

.btn-remove:hover {
  background-color: #ffebee;
}

.bookmark-content {
  flex: 1;
}

.bookmark-content h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #333;
  font-size: 1.1rem;
}

.bookmark-content p {
  color: #555;
  margin-bottom: 1rem;
  font-size: 0.9rem;
  line-height: 1.5;
}

.card-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.tag {
  padding: 0.25rem 0.5rem;
  background-color: #f0f0f0;
  border-radius: 12px;
  font-size: 0.75rem;
  color: #666;
}

.bookmark-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 1rem;
}

.btn-view-card {
  padding: 0.5rem 1rem;
  background-color: #2196F3;
  color: white;
  border-radius: 4px;
  text-decoration: none;
  font-size: 0.9rem;
}

.btn-view-card:hover {
  background-color: #1976D2;
}

.bookmark-date {
  font-size: 0.8rem;
  color: #888;
}

/* 分页控件样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 2rem;
}

.btn-page {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
}

.btn-page:hover:not(:disabled) {
  background-color: #f0f0f0;
}

.btn-page:disabled {
  color: #999;
  cursor: not-allowed;
}

.page-info {
  color: #666;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    gap: 1rem;
  }
  
  .filter-group {
    width: 100%;
  }
  
  .bookmarks-grid {
    grid-template-columns: 1fr;
  }
  
  .bookmark-footer {
    flex-direction: column;
    gap: 0.75rem;
    align-items: flex-start;
  }
}
</style> 